<?php
/*
 +----------------------------------------------------------------------
 + Title        : Test 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2019/5/30 23:35
 + Last-time    : 2019/5/30 23:35+ 86187
 + Desc         : Test
 +----------------------------------------------------------------------
*/


namespace app\admin\behavior;


use app\admin\service\NodeService;
use app\api\service\Token;
use library\tools\Node;
use think\Request;
use think\Response;

class Log
{
    public function run($param)
    {
        if(is_json($param->getContent())){
            $this->write( $param->getContent());
        }
        return true;
    }

    /**
     * 写入操作日志.
     *
     * @param string $action
     * @param string $content
     *
     * @return bool
     */
    public  function write( $response)
    {
        $node = Node::current();
        $action = $this-> getNodeName($node);
        $content = \think\facade\Request::method();
        $auth = \think\facade\Request::header('authorization');
        $username = \PHP_SAPI === 'cli' ? 'cli' : (string) session('user.username');
        if($auth && $users =  (new Token())->check($auth)){
            $username = $users->user->username.'['.$users->user->id.']';
        }

        $data = [
            'node'        => $node,
            'geoip'       => \PHP_SAPI === 'cli' ? '127.0.0.1' : request()->ip(),
            'action'      => $action,
            'content'     => $content,
            'username'    => $username,
            'request'     => json_encode(\request()->param(), JSON_UNESCAPED_UNICODE),
            'response'    => $response,
            'request_at'  => get_microtime_format( \think\facade\Request::time(true)),
            'response_at' => get_microtime_format(microtime(true))
        ];

        try {
            db('SystemLog')->insert($data);
        } catch (\Exception $e) {
            $res =  $e->getMessage();

        }
        return true;
    }

    public function getNodeName($node , $update=false ){

        $nodes = NodeService::getAuthList();
        return isset($nodes[$node]) ? $nodes[$node] : $node;

    }

}